<script lang="ts" setup>
  import { onMounted, ref } from 'vue';
  import dayjs from 'dayjs';
  import { getOrderList, startRefund } from '@/api/finance';
  import useTable from '@/hooks/table';
  import { Modal, Message } from '@arco-design/web-vue';
  import { UserOrder, UserOrderSearchParams } from '@/types/finance';
  import {
    OrderBusinessTypes,
    PayStatus,
    OrderRefundStatus,
  } from '@/config/finance';
  import SearchForm from './search-form.vue';
  import ExportOrder from './export-order.vue';

  const { pager, loading, total, list } = useTable<UserOrder>();

  const searchParams = ref<UserOrderSearchParams>({});

  const getData = async () => {
    loading.value = true;
    try {
      const res = await getOrderList({
        ...pager.value,
        ...searchParams.value,
      });
      total.value = res?.data?.data?.total || 0;
      list.value = res?.data?.data?.list || [];
    } finally {
      loading.value = false;
    }
  };

  const handleSearch = (params: UserOrderSearchParams) => {
    pager.value.pageIndex = 1;
    searchParams.value = params;
    getData();
  };

  const handlePageIndexChanged = (pageIndex: number) => {
    pager.value.pageIndex = pageIndex;
    getData();
  };

  onMounted(() => {
    getData();
  });

  const tryToRefund = (order: UserOrder) => {
    Modal.confirm({
      title: '提示',
      content: '确认退款？',
      async onBeforeOk() {
        try {
          await startRefund(order.number);
          Message.success('已发起退款');
          getData();
          return true;
        } finally {
          // do nothing
        }
      },
    });
  };

  const exporting = ref(false);
</script>

<template>
  <div style="padding: 20px">
    <a-row :gutter="[20, 20]">
      <a-col>
        <a-card title="账单管理" :bordered="false">
          <SearchForm @submit="handleSearch" />
        </a-card>
      </a-col>

      <a-col>
        <a-card :bordered="false">
          <div style="margin-bottom: 12px; text-align: right">
            <a-button @click="exporting = true">
              <template #icon><icon-download /></template>
              导出订单
            </a-button>
          </div>
          <a-table
            :bordered="{ cell: true }"
            :data="list"
            :loading="loading"
            :pagination="{
              total,
              current: pager.pageIndex,
              pageSize: pager.pageSize,
              showTotal: true,
              showJumper: true,
            }"
            @page-change="handlePageIndexChanged"
          >
            <template #columns>
              <a-table-column title="用户" :width="200">
                <template #cell="{ record }">
                  <div>
                    {{ record.user?.nickname }}
                    {{ record.user?.sex ? '男' : '女' }}
                  </div>
                  <div style="font-size: 12px; color: var(--color-text-2)">
                    {{ record.user?.idNo }}
                  </div>
                </template>
              </a-table-column>
              <a-table-column title="订单号" :width="200" data-index="number" />
              <a-table-column title="支付金额" :width="120">
                <template #cell="{ record }">
                  ￥{{ (record.amount / 100).toFixed(2) }}
                </template>
              </a-table-column>
              <a-table-column title="类型" :width="120">
                <template #cell="{ record }">
                  {{ OrderBusinessTypes[record.business] }}
                  <div
                    v-if="record.business === 2"
                    style="font-size: 12px; color: var(--color-text-2)"
                  >
                    {{ record.game?.name }}
                  </div>
                </template>
              </a-table-column>
              <a-table-column title="支付状态" :width="200">
                <template #cell="{ record }">
                  <div>{{ PayStatus[record.status] }}</div>
                  <div style="font-size: 12px; color: var(--color-text-2)">
                    创建时间：{{
                      dayjs(record.gmtCreate).format('YYYY/MM/DD HH:mm:ss')
                    }}
                  </div>
                </template>
              </a-table-column>
              <a-table-column title="退款状态" :width="200">
                <template #cell="{ record }">
                  <div>
                    {{
                      OrderRefundStatus[
                        record.refundStatus as keyof typeof OrderRefundStatus
                      ] || '无'
                    }}
                  </div>
                  <template v-if="record.refundStatus">
                    <div
                      v-if="record.refundStartTime"
                      style="font-size: 12px; color: var(--color-text-2)"
                    >
                      发起时间：{{
                        dayjs(record.refundStartTime).format(
                          'YYYY/MM/DD HH:mm:ss'
                        )
                      }}
                    </div>
                    <div
                      v-if="record.refundEndTime"
                      style="font-size: 12px; color: var(--color-text-2)"
                    >
                      结束时间：{{
                        dayjs(record.refundEndTime).format(
                          'YYYY/MM/DD HH:mm:ss'
                        )
                      }}
                    </div>
                  </template>
                </template>
              </a-table-column>
              <a-table-column
                title="操作"
                :width="100"
                fixed="right"
                align="center"
              >
                <template #cell="{ record }">
                  <a-link
                    :disabled="!!record.refundStatus"
                    @click="tryToRefund(record)"
                  >
                    发起退款
                  </a-link>
                </template>
              </a-table-column>
            </template>
          </a-table>
        </a-card>
      </a-col>
    </a-row>

    <ExportOrder v-if="exporting" @close="exporting = false" />
  </div>
</template>
